/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode *root)
    {
        if (root == nullptr)
        {
            return {};
        }
        vector<vector<int>> result;
        vector<TreeNode *> layer{root};
        bool reverse = false;
        while (!layer.empty())
        {
            vector<TreeNode *> nextLayer;
            result.push_back({});
            for (auto node : layer)
            {
                if (node->left != nullptr)
                {
                    nextLayer.push_back(node->left);
                }
                if (node->right != nullptr)
                {
                    nextLayer.push_back(node->right);
                }
                result.back().push_back(node->val);
            }
            if (reverse)
            {
                std::reverse(result.back().begin(), result.back().end());
            }
            reverse = !reverse;
            layer.swap(nextLayer);
        }
        return result;
    }
};